package com.dream.myqiyi.image.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.dream.myqiyi.util.Base64.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;

public class ImageUtil {

	/**
	 * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
	 * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
	 * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
	 * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
	 * 
	 * @param imagePath
	 *            图像的路径
	 * @param width
	 *            指定输出图像的宽度
	 * @param height
	 *            指定输出图像的高度
	 * @return 生成的缩略图
	 */
	public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null 
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false
		// 计算缩放比
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		options.inPreferredConfig = Bitmap.Config.ARGB_4444;
		options.inPurgeable = true;
		options.inInputShareable = true;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	public static Bitmap getImageThumbnail(String imagePath, int width) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null 
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false
		// 计算缩放比
		int h = options.outHeight;
		int w = options.outWidth;
		float be = (float)w / (float)width;
		if (be <= 0) {
			be = 1;
		}
		int height = (int)(options.outHeight / be);
		options.inSampleSize = (int)be;
		options.inPreferredConfig = Bitmap.Config.ARGB_4444;
		options.inPurgeable = true;
		options.inInputShareable = true;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,	ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		
//		File myCaptureFile = new File(imagePath);
//        BufferedOutputStream bos;
//		try {
//			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
//			bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
//			bos.flush();
//			bos.close();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		return bitmap;
	}

	public static Bitmap getImageThumbnail(Bitmap srcBitmap, int width) {
		// 计算缩放比
		int be = srcBitmap.getWidth() / width;
		if (be <= 0) {
			be = 1;
		}
		int height = srcBitmap.getHeight() / be;
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		Bitmap bitmap = ThumbnailUtils.extractThumbnail(srcBitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}
	
	public static Bitmap scaleBitmap(String imagePath, int scaleWidth, int scaleHeight) {
		File imageFile = new File(imagePath);
		if (!imageFile.exists()) {
			return null;
		}
		
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null 
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false
		// 计算缩放比
		int h = options.outHeight;
		int w = options.outWidth;

		options.inPreferredConfig = Bitmap.Config.RGB_565;   
		options.inPurgeable = true;  
		options.inInputShareable = true;  
		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);

		// 创建操作图片用的Matrix对象    
        Matrix matrix = new Matrix();    
        // 计算缩放比例    
        float sx= ((float) scaleWidth / w);    
        float sy= ((float) scaleHeight / h);    
        // 设置缩放比例    
        matrix.postScale(sx, sy);    
        // 建立新的bitmap，其内容是对原bitmap的缩放后的图   
        Bitmap scaleBmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);    
        return scaleBmp;    
    }    

    /** 
     * @param 将图片内容解析成字节数组 
     * @param inStream 
     * @return byte[] 
     * @throws Exception 
     */  
    public static byte[] readStream(InputStream inStream) throws Exception {  
        byte[] buffer = new byte[1024];  
        int len = -1;  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        while ((len = inStream.read(buffer)) != -1) {  
            outStream.write(buffer, 0, len);  
        }  
        byte[] data = outStream.toByteArray();  
        outStream.close();  
        inStream.close();  
        return data;  
  
    }  
    
    /** 
     * @param 将图片内容解析成字节数组 
     * @param inStream 
     * @return byte[] 
     * @throws Exception 
     */  
    public static byte[] readStream(String imagefile) {  
    	File file = new File(imagefile);
    	if (!file.exists()) {
    		return null;
    	}
    		
    	FileInputStream in = null;
        try {
            // 一次读一个字节
            in = new FileInputStream(file);
            byte[] buffer = new byte[1024];  
            int len = -1;  
            ByteArrayOutputStream out = new ByteArrayOutputStream();  
            while ((len = in.read(buffer)) != -1) {  
            	out.write(buffer, 0, len);  
            }  
            byte[] data = out.toByteArray();  
            out.close();  
            in.close();
            return data;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void writeStream(String filename, byte[] stream) {
    	File file = new File(filename);
    	try {
    		FileOutputStream out = new FileOutputStream(file);
    		out.write(stream);
    		out.close();
    	} catch (IOException e) {
            e.printStackTrace();
            return ;
        }   	
    }

    /** 
     * @param 将字节数组转换为ImageView可调用的Bitmap对象 
     * @param bytes 
     * @param opts 
     * @return Bitmap 
     */  
    public static Bitmap getPicFromBytes(byte[] bytes,  
            BitmapFactory.Options opts) {  
        if (bytes != null)  
            if (opts != null)  
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,  
                        opts);  
            else  
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
        return null;  
    }  
    /** 
     * @param 图片缩放 
     * @param bitmap 对象 
     * @param w 要缩放的宽度 
     * @param h 要缩放的高度 
     * @return newBmp 新 Bitmap对象 
     */  
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){  
        int width = bitmap.getWidth();  
        int height = bitmap.getHeight();  
        Matrix matrix = new Matrix();  
        float scaleWidth = ((float) w / width);  
        float scaleHeight = ((float) h / height);  
        matrix.postScale(scaleWidth, scaleHeight);  
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,  
                matrix, true);  
        return newBmp;  
    }  
      
    /** 
     * 把Bitmap转Byte 
     * @Author HEH 
     * @EditTime 2010-07-19 上午11:45:56 
     */  
    public static byte[] Bitmap2Bytes(Bitmap bm){  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);  
        return baos.toByteArray();  
    }  
    /** 
     * 把字节数组保存为一个文件 
     * @Author HEH 
     * @EditTime 2010-07-19 上午11:45:56 
     */  
    public static File getFileFromBytes(byte[] b, String outputFile) {  
        BufferedOutputStream stream = null;  
        File file = null;  
        try {  
            file = new File(outputFile);  
            FileOutputStream fstream = new FileOutputStream(file);  
            stream = new BufferedOutputStream(fstream);  
            stream.write(b);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (stream != null) {  
                try {  
                    stream.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }  
        return file;  
    }  

}
